package org.person.gift.listener;

import com.alibaba.fastjson.JSONArray;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.person.gift.constants.GiftConstants;
import org.person.gift.dto.GiftOnsaleMsgQueueDto;
import org.person.gift.service.IGoodsSpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@RocketMQTransactionListener(txProducerGroup = GiftConstants.GIFT_ONSALE_TX_PRODUCER_GROUP)
public class SpuOnsaleRocketMQLocalTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IGoodsSpuService goodsSpuService;

    /**
     * 执行本地事务
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            //从消息对象中获取数据的字节对象
            byte[] bytes = (byte[])message.getPayload();
            //转化为字符串
            String jsonStr = new String(bytes,"utf-8");
            //转化为集合
            List<GiftOnsaleMsgQueueDto> spuOnsaleDtos = JSONArray.parseArray(jsonStr, GiftOnsaleMsgQueueDto.class);
            //修改数据库操作
            boolean result = goodsSpuService.executeOnsaleLocalTransactionOpr(spuOnsaleDtos);
            //添加上架操作日志 @TODO
            //生成静态化页面
            return result ? RocketMQLocalTransactionState.COMMIT
                    : RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return  RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            //从消息对象中获取数据的字节对象
            byte[] bytes = (byte[])message.getPayload();
            //转化为字符串
            String jsonStr = new String(bytes, StandardCharsets.UTF_8);
            //转化为集合
            List<GiftOnsaleMsgQueueDto> spuOnsaleDtos = JSONArray.parseArray(jsonStr, GiftOnsaleMsgQueueDto.class);
            //通过传递集合中的某个id查询数据库中该条数据的值是否修改就可确认回查
            Long spuNo = spuOnsaleDtos.get(1).getSpuNo();
            boolean result = goodsSpuService.checkExsitOnsaled(spuNo);
            return result ? RocketMQLocalTransactionState.COMMIT
                    : RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
